import { Request, Response, NextFunction } from 'express';
import { prisma } from '../../config/database';
import { BaseController } from '../../utils/autoBind';
import { ResponseUtils } from '../../utils/responseUtils';
import { BUSINESS_ERROR_CODES } from '../../utils/errorCodes';
import config from '@/config';

export class ClientPerformanceController extends BaseController {
  // 获取演出列表
  async getPerformanceList(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { page = 1, limit = 10, date, venue, status } = req.query;
      const skip = (Number(page) - 1) * Number(limit);

      const where: any = {};
      if (date) {
        // 处理日期查询，只关注日期部分，忽略时间
        const targetDate = new Date(date as string);
        targetDate.setHours(0, 0, 0, 0);
        const nextDay = new Date(targetDate);
        nextDay.setDate(nextDay.getDate() + 1);
        where.startTime = {
          gte: targetDate,
          lt: nextDay
        };
      }
      if (venue) where.venue = venue;
      if (status) where.status = status;

      const [performances, total] = await Promise.all([
        prisma.performance.findMany({
          where,
          skip: skip,
          take: Number(limit),
          orderBy: { startTime: 'asc' },
          select: {
            id: true,
            title: true,
            description: true,
            venue: true,
            floor: true,
            startTime: true,
            endTime: true,
            status: true,
            artist: {
              select: {
                id: true,
                name: true,
                avatar: true
              }
            }
          }
        }),
        prisma.performance.count({ where })
      ]);
      /** 头像路径 */
      performances.forEach((performance: any) => {
        performance.artist.avatar = `${config.server.appUrl}${performance.artist.avatar}`;
      });

      ResponseUtils.success(res, {
        items: performances,
        pagination: {
          total,
          page: Number(page),
          limit: Number(limit),
          totalPages: Math.ceil(total / Number(limit))
        }
      }, '获取演出列表成功');
    } catch (error) {
      next(error);
    }
  }

  // 获取演出详情
  async getPerformanceDetail(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      if(!id){
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.PERFORMANCE_NOT_FOUND, '演出不存在');
        return;
      }

      const performance = await prisma.performance.findUnique({
        where: { id: Number(id) },
        // 使用 any 跳过类型检查，等待 Prisma Client 重新生成后再恢复严格类型
        select: ({
          id: true,
          title: true,
          description: true,
          venue: true,
          floor: true,
          floorRef: {
            select: {
              id: true,
              venue: true,
              name: true,
              level: true,
              status: true
            }
          },
          startTime: true,
          endTime: true,
          status: true,
          maxCapacity: true,
          currentAttendance: true,
          artist: {
            select: {
              id: true,
              name: true,
              avatar: true,
              description: true,
              bannerImage: true,
              country: true,
              // 包含艺人的代表作品
              works: {
                where: {
                  isRepresentative: true
                },
                select: {
                  id: true,
                  title: true,
                  duration: true,
                  description: true,
                  releaseDate: true,
                  isRepresentative: true,
                  audioUrl: true // 添加音频字段
                },
                orderBy: {
                  releaseDate: 'desc'
                },
                take: 5 // 只取前5个代表作品
              }
            }
          }
        } as any)
      });
      /** 头像路径 和 音频路径 */
      if (performance && (performance as any).artist) {
        // 处理头像路径
        if ((performance as any).artist.avatar) {
          (performance as any).artist.avatar = `${config.server.appUrl}${(performance as any).artist.avatar}`;
        }
        
        // 处理作品音频路径
        if ((performance as any).artist.works && Array.isArray((performance as any).artist.works)) {
          (performance as any).artist.works.forEach((work: any) => {
            if (work.audioUrl) {
              work.audioUrl = `${config.server.appUrl}${work.audioUrl}`;
            }
          });
        }
      }

      if (!performance) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.PERFORMANCE_NOT_FOUND, '演出不存在');
        return;
      }

      ResponseUtils.success(res, performance, '获取演出详情成功');
    } catch (error) {
      next(error);
    }
  }

  // 获取演出倒计时
  async getPerformanceCountdown(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;

      const performance = await prisma.performance.findUnique({
        where: { id: Number(id) },
        select: {
          id: true,
          title: true,
          startTime: true,
          status: true
        }
      });

      if (!performance) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.PERFORMANCE_NOT_FOUND, '演出不存在');
        return;
      }

      const now = new Date();
      const startTime = new Date(performance.startTime);
      let countdown = null;

      if (performance.status === 'COMPLETED' || performance.status === 'CANCELLED') {
        countdown = {
          status: performance.status,
          message: performance.status === 'COMPLETED' ? '演出已结束' : '演出已取消',
          milliseconds: 0
        };
      } else if (now > startTime) {
        countdown = {
          status: 'ONGOING',
          message: '演出进行中',
          milliseconds: 0
        };
      } else {
        const diff = startTime.getTime() - now.getTime();
        countdown = {
          status: 'SCHEDULED',
          message: '演出即将开始',
          milliseconds: diff,
          hours: Math.floor(diff / (1000 * 60 * 60)),
          minutes: Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)),
          seconds: Math.floor((diff % (1000 * 60)) / 1000)
        };
      }

      ResponseUtils.success(res, {
        performanceId: performance.id,
        performanceTitle: performance.title,
        countdown
      }, '获取演出倒计时成功');
    } catch (error) {
      next(error);
    }
  }
}